package com.startx.http.controller;

import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;

import com.startx.core.mvc.define.RequestMapping;
import com.startx.core.mvc.define.RequestMethod;
import com.startx.core.system.param.HttpBody;
import com.startx.core.system.param.HttpParam;
import com.startx.http.service.IDataEntryService;
import com.startx.http.system.annotation.RequireLogin;
import com.startx.http.system.exception.MiniException;
import com.startx.http.system.tool.ResponseBuilder;
import com.startx.http.system.tool.ResponseBuilder.HttpResponse;


@Controller
@RequestMapping("/data")
public class DataEntryController {

    @Inject
    private IDataEntryService dataEntryService;

    /**
     * 保存数据
     */
    @RequestMapping(value="/save",method={RequestMethod.POST})
    @RequireLogin
    public HttpResponse saveData(HttpParam param, HttpBody body) {
        try {
        	dataEntryService.doSaveDataEntry(param,body);
            return ResponseBuilder.successful();
        } catch (MiniException e) {
            return ResponseBuilder.build(e.getCode());
        }
    }
    
    /**
     * 获取数据
     */
    @RequestMapping(value="/get",method={RequestMethod.GET})
    @RequireLogin
    public HttpResponse getData(HttpParam param) {
        try {
        	Map<String,?> entry = dataEntryService.doGetDataEntry(param);
        	
        	HttpResponse response;
        	
        	if(entry.isEmpty()) {
        		return ResponseBuilder.successful();
        	}
        	
        	String key = param.getParam("key");
        	if(StringUtils.isNotBlank(key)) {
        		response = ResponseBuilder.build(entry.get(key));
        	} else {
        		response = ResponseBuilder.build(entry);
        	}
        	
            return response;
        } catch (MiniException e) {
            return ResponseBuilder.build(e.getCode());
        }
    }
}
